package com.treeliked.netdiskdemo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.treeliked.netdiskdemo.model.Response;
import com.treeliked.netdiskdemo.model.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截请求，检查session是否有效
 *
 * @author lqs2
 * @date 2018/12/10, Mon
 */
public class MyInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(MyInterceptor.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = (String) request.getSession().getAttribute("user-name");
        if (!StringUtils.isEmpty(username)) {
            return true;
        } else {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/json;charset=utf-8");
            Response resp = new Response();
            resp.setCode(ResultCode.UNAUTHORIZED);
            resp.setMessage("会话超时，请重新登录");
            response.setStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
            response.getWriter().write(objectMapper.writeValueAsString(resp));
            return false;
        }
    }
}
